<?php 

namespace app\admin\controller;
use app\common\model\GoodsAttr;
use app\common\model\GoodsAttribute as GoodsAttributeModel;
use app\admin\controller\Base;
use app\admin\validate\GoodsAttributeValidate;
use app\admin\event\GoodsAttributeEvent;
use app\common\utils\JsonService;
use think\facade\View;

class GoodsAttribute extends Base{

    /**
    * 新增商品属性
    * @return mixed
    */
    public function create(){
        if($this->request->isajax()){
            $post = $this->request->post();
            $validate = new GoodsAttributeValidate;
            if(!$validate->scene('add')->check($post)) {
                return JsonService::error($validate->getError());
            }
            return GoodsAttributeEvent::createGoodsAttribute($post);
        }
        $goodsType = \app\common\model\GoodsType::getAll();
        return View::fetch('create',['goodsType'=>$goodsType]);
    }

    /**
    * 编辑商品属性
    * @return mixed
    */
    public function update(){
        if($this->request->isAjax()){
            $post = $this->request->post();
            $validate = new GoodsAttributeValidate;
            if(!$validate->scene('edit')->check($post)) {
                return JsonService::error($validate->getError());
            }
            return GoodsAttributeEvent::updateGoodsAttribute($post);
        }

        $attr_id = $this->request->get('attr_id');
        $model = $this->findModel($attr_id);
        $goodsType = \app\common\model\GoodsType::getAll();
        return View::fetch('update',[
            'model'=>$model,
            'goodsType'=>$goodsType
        ]);
    }

    /**
    * 商品属性列表

    * @return mixed
    */
    public function index(){
        $dataProvider = GoodsAttributeEvent::goodsAttributeList();
        $goodsType = \app\common\model\GoodsType::getAll();
        return View::fetch('index',['dataProvider'=>$dataProvider,'goodsType'=>$goodsType]);
    }


    /*
    * 删除商品属性
    */
    public function delete(){
        if($this->request->isAjax()){
            $attr_id = $this->request->param('attr_id');
            try{
                $model = $this->findModel($attr_id);
                $model->delete();
                //把goods_attr表中的属性也删除
                GoodsAttr::delByWhere(['attr_id'=>$attr_id]);
            }catch (\Exception $ex){
                return JsonService::error($ex->getMessage());
            }
            return JsonService::success('删除成功');
        }
    }

    /**
    * 得到模型
    *
    * @param int $id
    * @param array $where
    *
    * @return array|false|\PDOStatement|string|\think\Model
    */
    public function findModel($id,$where = [])
    {
        if (empty($id) && empty($where)) {
            throw new \think\exception\RouteNotFoundException();
        }
        return GoodsAttributeModel::findModel($id, $where);
    }

}
